package com.shidaimanong.demo.down;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

/**
 * 学编程，关注：十代码农
 * 抖音、快手、B站、西瓜视频、今日头条
 */
public class DownPicDemo2 {
    public static void main(String[] args) throws Exception {
        List<String> list = Arrays.asList(
                "http://n.sinaimg.cn/sinakd20210505ac/388/w640h548/20210505/38f6-kppteat0006665.jpg",
                "https://inews.gtimg.com/newsapp_bt/0/13475652634/1000",
                "https://inews.gtimg.com/newsapp_bt/0/13548436237/1000");
        for (int i = 0; i < list.size(); i++) {
            download(list.get(i), i + "");
        }
    }

    private static void download(String urlString, String picName) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 设置下载数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        String filename = picName + ".jpg";  //设置下载图片名称
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取数据并写入文件
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭链接
        os.close();
        is.close();
    }
}